package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.entry.tables.ShoppingCartGoodsTable;
import com.gdk.ksoft.ui.sales.GiveOtherTypeActivity;
import com.gdk.ksoft.ui.sales.GiveSelfTypeActivity;
import com.gdk.ksoft.ui.works.adapters.PplaceOrderAdapter;
import com.gdk.ksoft.ui.works.models.FworkGoodsOrderModel;
import com.gdk.ksoft.assembly.dbhelper.FworkDbHelper;
import com.gdk.ksoft.assembly.dialog.FixSingleProductDialog;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;
import com.lidroid.xutils.view.annotation.event.OnItemLongClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 客户开单页面
 */
public class PlaceOrderActivity extends Activity {

    public static final int REQ_CODE_FIND_GOODS = 0x00001;//查找商品的请求码

    @ViewInject(R.id.pplaceOrder_txtTitle)private TextView txtTitle;//标题栏
    @ViewInject(R.id.pplaceOrder_lstOrders)private ListView lstOrders;//客户订单商品
    @ViewInject(R.id.pplaceOrder_txtGoodsCount)private TextView txtGoodsCount;//商品数量
    @ViewInject(R.id.pplaceOrder_txtGoodsKinds)private TextView txtGoodsKinds;//商品种类
    @ViewInject(R.id.pplaceOrder_txtMoney)private TextView txtMoney;//总金额

    private DbUtils dbUtils;//数据库操作对象
    private String customerPriceName;//客户价格名称
    private int netCustomerId = 0,netAddressId = 0;//客户网络ID,客户送货地址网络ID
    private int pieceNum = 0,singleNum = 0,kindsNum = 0;//件数,散数,种类数
    private double totalMoney = 0.0;//总金额
    private int pageCount = 0,currentPageIndex = 0;//当前页码总数及当前页码
    private static final int PAGE_COUNT = 20;//每页商品数量
    private List<FworkGoodsOrderModel> goodslist = new ArrayList<FworkGoodsOrderModel>();//商品列表集合
    private List<FworkGoodsOrderModel> tmpGoodslist = new ArrayList<FworkGoodsOrderModel>();//商品临时列表集合
    private PplaceOrderAdapter goodsAdapter;//商品数据适配器

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_place_order);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        goodsAdapter = new PplaceOrderAdapter(this,goodslist);
        lstOrders.setAdapter(goodsAdapter);
        lstOrders.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                int lastPos = view.getLastVisiblePosition();
                if(scrollState == SCROLL_STATE_IDLE && lastPos == view.getCount()-1){
                    currentPageIndex ++;
                    if(currentPageIndex > pageCount-1){
                        currentPageIndex = pageCount - 1;
                        return;
                    }
                    int backPageIndex = currentPageIndex + 1;
                    int dataLen = tmpGoodslist.size();//获取数据总数
                    if(currentPageIndex == pageCount - 1){
                        goodslist.addAll(tmpGoodslist.subList(currentPageIndex*PAGE_COUNT,
                                dataLen%PAGE_COUNT==0?backPageIndex*PAGE_COUNT
                                        :currentPageIndex*PAGE_COUNT+dataLen%PAGE_COUNT));//获取最后一页的数据
                    }else{
                        goodslist.addAll(tmpGoodslist.subList(currentPageIndex*PAGE_COUNT,backPageIndex*PAGE_COUNT));
                    }
                    goodsAdapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        initActivity();//初始化页面参数
    }

    /**
     * 初始化页面参数
     */
    public void initActivity(){
        Intent intent = getIntent();
        if(intent!=null){//获取页面传递数据
            netCustomerId = intent.getIntExtra("netCustomerId",0);
            netAddressId = intent.getIntExtra("netAddressId",0);
            customerPriceName = intent.getStringExtra("priceName");
            txtTitle.setText(intent.getStringExtra("customerName")+"订货单");
            queryAllOrderlst();//查询客户订单数据
        }
    }

    /**
     * 界面控件绑定点击事件
     * @param view
     */
    @OnClick(value={R.id.pplaceOrder_txtFindGoods,R.id.pplaceOrder_txtDebt,R.id.pplaceOrder_txtStatistics,
            R.id.pplaceOrder_imgClearOrder,R.id.pplaceOrder_txtBuy1,R.id.pplaceOrder_txtBuy2,R.id.pplaceOrder_txtBuy3,
            R.id.pplaceOrder_txtBuy4}
    )
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.pplaceOrder_txtFindGoods://找商品
                Intent intent = new Intent(this,FindGoodsActivity.class);
                intent.putExtra("netCustomerId",netCustomerId);//传递客户网络ID
                intent.putExtra("priceName", customerPriceName);//传递客户价格名称
                intent.putExtra("netAddressId",netAddressId);//送货地址网络ID
                startActivityForResult(intent, REQ_CODE_FIND_GOODS);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
            case R.id.pplaceOrder_txtStatistics://下订单
                if(isShoppingCartGoodsBlank()) return;
                Intent cintent = new Intent(this,OrderConfirmationActivity.class);
                cintent.putExtra("netCustomerId",netCustomerId);//传递客户网络ID
                cintent.putExtra("netAddressId",netAddressId);//传递送货地址网络ID
                cintent.putExtra("goodsPieceNum",pieceNum);//传递商品件数
                cintent.putExtra("goodsSingleNum",singleNum);//传递商品散数
                cintent.putExtra("goodsKindsNum",kindsNum);//传递商品种类
                cintent.putExtra("goodsTotalMoney",totalMoney);//传递金额数
                startActivity(cintent);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
            case R.id.pplaceOrder_txtDebt://收款
                if(isShoppingCartGoodsBlank()) return;
                Intent ointent = new Intent(this, OrderStatisticsActivity.class);
                ointent.putExtra("netCustomerId",netCustomerId);//传递客户网络ID
                ointent.putExtra("netAddressId",netAddressId);//传递送货地址网络ID
                ointent.putExtra("goodsPieceNum",pieceNum);//传递商品件数
                ointent.putExtra("goodsSingleNum",singleNum);//传递商品散数
                ointent.putExtra("goodsKindsNum",kindsNum);//传递商品种类
                ointent.putExtra("goodsTotalMoney",totalMoney);//传递金额数
                ointent.putExtra("goodsCount",txtGoodsCount.getText().toString());//商品数量
                startActivity(ointent);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.pplaceOrder_imgClearOrder://清空购物车
                if(isShoppingCartGoodsBlank()) return;
                PplaceOrderAdapter adapter = (PplaceOrderAdapter)lstOrders.getAdapter();
                final List<FworkGoodsOrderModel> goodslst = adapter.getList();
                if(goodslst == null || goodslst.size() == 0) return;//没有商品可清除
                final MessageBox msgBox = new MessageBox(this);
                msgBox.setMessage("确定要清空购物车吗？");
                msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        msgBox.dismiss();
                        if(v.getId() == MessageBox.ID_DIALOG_BUTTON_OK){//如果触发的是确定键
                            clearShoppingCart(netCustomerId,netAddressId);//清空购物车操作
                        }
                    }
                });
                msgBox.show();
                break;
            case R.id.pplaceOrder_txtBuy1://买赠本品
                Intent intentSelf = new Intent(this,GiveSelfTypeActivity.class);
                intentSelf.putExtra("netCustomerId",netCustomerId);//传递客户网络ID
                intentSelf.putExtra("priceName", customerPriceName);//传递客户价格名称
                intentSelf.putExtra("netAddressId",netAddressId);//送货地址网络ID
                startActivity(intentSelf);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
            case R.id.pplaceOrder_txtBuy2://买赠它品
                Intent intentOther = new Intent(this,GiveOtherTypeActivity.class);
                intentOther.putExtra("netCustomerId",netCustomerId);//传递客户网络ID
                intentOther.putExtra("priceName", customerPriceName);//传递客户价格名称
                intentOther.putExtra("netAddressId",netAddressId);//送货地址网络ID
                startActivity(intentOther);
                overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
                break;
            case R.id.pplaceOrder_txtBuy3://组合
                break;
            case R.id.pplaceOrder_txtBuy4://订货会
                break;
        }
    }

    /**
     * 购物商品是否是空白的
     * @return
     */
    public boolean isShoppingCartGoodsBlank(){
        boolean b = lstOrders.getCount()<=0;
        if(b) Toast.makeText(this,"当前购物车没有商品，不可操作!",Toast.LENGTH_SHORT).show();
        return b;
    }

    /**
     * 列表单击事件，修改数据
     * @param av
     * @param view
     * @param position
     * @param itemId
     */
    @OnItemClick(value = {R.id.pplaceOrder_lstOrders})
    public void onItemClick(AdapterView<?> av,View view,int position,long itemId){
        final FworkGoodsOrderModel item = (FworkGoodsOrderModel) lstOrders.getItemAtPosition(position);
        if(TextUtils.isEmpty(item.cx_bz)||item.cx_bz.equals("0")) {
            try {
                FixSingleProductDialog dialog = new FixSingleProductDialog(this, item);
                dialog.setOnValueChangedListener(new FixSingleProductDialog.OnValueChangedListener() {
                    @Override
                    public void onValueChanged() {
                        queryAllOrderlst();//重新查询一次数据
                    }
                });
                dialog.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            Toast.makeText(this,"促销商品，不可修改!",Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 列表项长按事件，删除数据
     * @param parent
     * @param view
     * @param position
     * @param id
     * @return
     */
    @OnItemLongClick(value={R.id.pplaceOrder_lstOrders})
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        final FworkGoodsOrderModel item = (FworkGoodsOrderModel) lstOrders.getItemAtPosition(position);
        if(!TextUtils.isEmpty(item.cx_bz) && !item.cx_bz.equals("0"))
            showDelCxDialog(item);//提示删除促销商品的数据
        else showDelDialog(item);//显示删除记录的提示框
        return true;
    }

    /**
     * 显示删除记录的提示框
     */
    public void showDelDialog(final FworkGoodsOrderModel item){
        final MessageBox messageBox = new MessageBox(this);
        messageBox.setMessage("确定要删除该条记录吗?");
        messageBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        messageBox.dismiss();
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        try {
                            FworkDbHelper.deleteShoppingCartGoods(dbUtils, item.shoppingCartGoodsId);//删除商品购物车记录
                            Toast.makeText(PlaceOrderActivity.this, "删除记录成功!", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            Toast.makeText(PlaceOrderActivity.this, "删除记录失败!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }finally {
                            queryAllOrderlst();//重新查询一次数据
                        }
                        messageBox.dismiss();
                        break;
                }
            }
        });
        messageBox.show();
    }

    /**
     * 显示删除所有促销记录的提示框
     * @param item
     */
    public void showDelCxDialog(final FworkGoodsOrderModel item){
        final MessageBox messageBox = new MessageBox(this);
        messageBox.setMessage("确定要删除该条记录吗?删除该表记录将会删除与之相关的所有促销的商品数据?!");
        messageBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case MessageBox.ID_DIALOG_BUTTON_CANCEL:
                        messageBox.dismiss();
                        break;
                    case MessageBox.ID_DIALOG_BUTTON_OK:
                        try {
                            //删除该促销标识下的所有商品
                            dbUtils.delete(ShoppingCartGoodsTable.class, WhereBuilder.b("cx_bz", "=", item.cx_bz));
                            Toast.makeText(PlaceOrderActivity.this, "删除记录成功!", Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            Toast.makeText(PlaceOrderActivity.this, "删除记录失败!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }finally {
                            queryAllOrderlst();//重新查询一次数据
                        }
                        messageBox.dismiss();
                        break;
                }
            }
        });
        messageBox.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_CODE_FIND_GOODS) queryAllOrderlst();//查询客户订单数据
    }

    /**
     * 查询客户订单数据
     */
    public void queryAllOrderlst(){
        new AsyncTask<Void,Void,Void>(){
            private String error = null;
            private List<FworkGoodsOrderModel> lst = null;
            private HashMap<String,Object> objectHashMap = null;
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    lst = FworkDbHelper.findAllOrderlst(dbUtils,netCustomerId, netAddressId,-1);
                    objectHashMap = FworkDbHelper.findAllOrderlstInfo(dbUtils,netAddressId);
                }catch (Exception e){
                    error = e.getMessage();
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                resetGoodsList();//重置商品列表
                if(error!=null||objectHashMap==null||lst==null||lst.size()<=0){
                    txtGoodsCount.setText("0件0散");
                    txtGoodsKinds.setText("0种");
                    txtMoney.setText("0.00元");
                    if(error!=null||objectHashMap==null) {
                        Toast.makeText(PlaceOrderActivity.this, "查询出错!", Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                int dataLen = lst.size();//数据总数量
                tmpGoodslist.addAll(lst);//添加所有商品数据到集合
                currentPageIndex = 0;//页码置0
                pageCount = dataLen%PAGE_COUNT == 0?dataLen/PAGE_COUNT:dataLen/PAGE_COUNT+1;//获取页码
                if(pageCount == 1){//如果只有一页的数据
                    goodslist.addAll(tmpGoodslist.subList(0,dataLen%PAGE_COUNT==0?PAGE_COUNT:dataLen%PAGE_COUNT));//获取第一页的数据
                }else{
                    goodslist.addAll(tmpGoodslist.subList(0,PAGE_COUNT));
                }
                goodsAdapter.notifyDataSetChanged();//刷新列表
                lstOrders.setSelection(0);//默认选中第一项
                pieceNum = Integer.parseInt(objectHashMap.get("totalJs").toString());
                singleNum = Integer.parseInt(objectHashMap.get("totalSingle").toString());
                totalMoney = Double.parseDouble(objectHashMap.get("totalMoney").toString());
                kindsNum = Integer.parseInt(objectHashMap.get("totalKinds").toString());
                txtGoodsCount.setText(pieceNum+"件"+singleNum+"散");
                txtGoodsKinds.setText(kindsNum+"种");
                txtMoney.setText(FormatUtils.exactNumber(totalMoney,"0.00")+"元");
            }
        }.execute();
    }

    /**
     * 重置商品列表
     */
    public void resetGoodsList(){
        tmpGoodslist.clear();//清空临时数据源
        goodslist.clear();//清空商品数据
        goodsAdapter.notifyDataSetChanged();//刷新列表
        currentPageIndex = 0;
        pageCount = 0;
    }

    /**
     * 清空购物车
     * @param customerId  客户网络ID
     * @param deliverGoodsId 送货地址网络ID
     */
    public void clearShoppingCart(final int customerId,final int deliverGoodsId){
        new AsyncTask<Void,Void,Void>(){
            private String errorMessage = null;
            @Override
            protected Void doInBackground(Void... params) {
                try{
                    FworkDbHelper.deleteAllOrderlst(dbUtils,customerId,deliverGoodsId);
                }catch (Exception e){
                    e.printStackTrace();
                    errorMessage = e.getMessage();
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(errorMessage == null){
                    queryAllOrderlst();//如果删除成功，再次查询一下购物车商品数据
                }else{
                    Toast.makeText(PlaceOrderActivity.this,"清空购物车失败!原因："+errorMessage,Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    @Override
    protected void onResume() {
        super.onResume();
        queryAllOrderlst();//查询购物车商品信息
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pplaceOrder_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
